<template>
  <el-dialog v-model:model-value="visible" :append-to-body="true"
             :close-on-click-modal="false"
             title="场景管理" width="700px" @close="handleCancel">
    <div class="scene-name">您可通过拖拽管理标签</div>
    <flexbox class="scene-list">
      <div class="scene-list-box">
        <flexbox class="scene-list-head">
          <el-checkbox :indeterminate="isleftIndeterminate" v-model="checkleftAll" @change="handleleftCheckAllChange"/>
          <div class="scene-list-head-name">显示的标签</div>
          <div class="scene-list-head-detail">{{ leftCheckItems.length + '/' + checkedLeftData.length }}</div>
        </flexbox>
        <div class="scene-list-body">
          <flexbox v-for="(item, index) in checkedLeftData" v-if="item && item.isSystem == 1"
                   :key="index" class="list-item">
            <div :class="{'default-mark-active': item.sceneId == defaultId}" class="default-mark"/>
            <el-checkbox v-model="item.check" :disabled="true" class="list-item-check" @change="leftCheckItemChange"/>
            <div class="list-item-name">{{ item.name }}</div>
            <div class="list-item-handle">
              <el-dropdown @command="defaultHandle(arguments[0], item)">
                <i class="el-icon-arrow-down"/>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="default">设置为默认标签</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </flexbox>
          <draggable v-model="checkedLeftData" item-key="value" :move="leftMove"
                     :options="{group: 'list',forceFallback:false, fallbackClass:'draggingStyle'}"
                     style="min-height: 100px;" @end="leftMoveEnd">
            <template v-slot:item="{element, index}">
              <flexbox v-if="element.isSystem != 1" class="list-item">
                <div :class="{'default-mark-active': element.sceneId == defaultId}" class="default-mark"/>
                <el-checkbox v-model="element.check" class="list-item-check" @change="leftCheckItemChange"/>
                <div class="list-item-name">{{ element.name }}</div>
                <div class="list-item-handle">
                  <i class="el-icon-edit" @click="itemHandle('edit', element, index)"/>
                  <i class="el-icon-delete" @click="itemHandle('delete', element, index)"/>
                  <el-dropdown @command="defaultHandle(arguments[0], item)">
                    <i class="el-icon-arrow-down"/>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="default">设置为默认标签</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </flexbox>
            </template>

          </draggable>

        </div>
      </div>
      <div class="scene-middle-list">
        <el-button :class="{'scene-middle-button-select':rightCheckItems.length > 0}"
                   :disabled="rightCheckItems.length == 0" class="scene-middle-left-button"
                   @click="changePositon('left')">
          <!--          <i class="el-icon-arrow-left scene-middle-icon"/>-->
          <el-icon>
            <ArrowLeft/>
          </el-icon>
        </el-button>
        <el-button :class="{'scene-middle-button-select':leftCheckItems.length > 0}"
                   :disabled="leftCheckItems.length == 0"
                   class="scene-middle-right-button"
                   @click="changePositon('right')">
          <!--          <i class="el-icon-arrow-right scene-middle-icon"/>-->
          <el-icon>
            <ArrowRight/>
          </el-icon>
        </el-button>
      </div>
      <div class="scene-list-box">
        <flexbox class="scene-list-head">
          <el-checkbox :indeterminate="isrightIndeterminate" v-model="checkrightAll"
                       @change="handlerightCheckAllChange"/>
          <div class="scene-list-head-name">隐藏的标签</div>
          <div class="scene-list-head-detail">{{ rightCheckItems.length + '/' + checkedRightData.length }}</div>
        </flexbox>
        <div class="scene-list-body">
          <draggable v-model="checkedRightData" item-key="value"
                     :move="rightMove" :options="{group: 'list',forceFallback:false, fallbackClass:'draggingStyle'}"
                     style="min-height: 100px;" @end="rightMoveEnd">
            <template v-slot:item="{element, index}">
              <flexbox class="list-item">
                <el-checkbox v-model="element.check" style="margin-left:9px;"
                             class="list-item-check" @change="rightCheckItemChange"/>
                <div class="list-item-name">{{ element.name }}</div>
              </flexbox>
            </template>
          </draggable>
        </div>
      </div>
    </flexbox>

    <div class="handle-bar">
      <div class="handle-bar-add" @click="addAndEditScene('add',{})">+ 新建场景</div>
    </div>

    <template v-slot:footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-debounce="handleConfirm" type="primary">保存</el-button>
      </div>
    </template>

    <SceneCreate :field-list="fieldList"
                 :crm-type="crmType" :dialog-visible.sync="showCreateScene"
                 :obj="filterObj" :name="filterName" :edit_id="filterEditId"
                 :is-default="filterDefault" @save-success="getSceneList"/>
  </el-dialog>
</template>

<script setup>
import crmTypeModel from "@/views/crm/model/crmTypeModel.js";

import {
  crmSceneSetIndexAPI,
  crmSceneSortAPI,
  crmSceneDefaultsAPI,
  crmSceneDeleteAPI,
  filterIndexfieldsAPI
} from '/src/api/crm/common.js'
import draggable from 'vuedraggable'
import SceneCreate from './MyCreateScene.vue'
import {ElMessage} from "element-plus"; // 新建编辑场景

defineOptions({
  name: 'ManageScene', // 场景 设置
})

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    required: true,
    default: false
  },
  /** 没有值就是全部类型 有值就是当个类型 */
  crmType: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['save-success', 'update:dialogVisible'])

const defaultId = ref('') // 默认场景id
const visible = ref(false) // 控制展示
const isleftIndeterminate = ref(false) // 标注头部是多选框效果
const checkleftAll = ref(false) // 关联全选操作多选框

const checkedLeftData = ref([]) // 数据源
const leftCheckItems = ref([]) // 选择的数据源

const isrightIndeterminate = ref(false)
const checkrightAll = ref(false)

const checkedRightData = ref([])
const rightCheckItems = ref([])

const moveItem = ref({}) // 移动中的item
const handlDefaultItem = ref({}) // 设置默认的中间item

/** 添加 编辑 场景 */
const showCreateScene = ref(false) // 展示场景添加
const fieldList = ref([])
const filterObj = ref({form: []}) // 筛选确定数据
const filterName = ref('')
const filterDefault = ref(false)
const filterEditId = ref('') // 编辑id


watch(() => props.dialogVisible, (val) => {
  visible.value = val
  if (val) {
    getSceneList()
  }
}, {
  deep: true,
  immediate: true
})


function getSceneList() {
  console.log("getSceneList", getSceneList)
  crmSceneSetIndexAPI({
    type: crmTypeModel[props.crmType]
  }).then(res => {
    checkedLeftData.value = res.data.data.value.map(item => {
      item.check = false
      item.data = !item.data ? {} : JSON.parse(item.data)
      return item
    })
    checkedRightData.value = res.data.data.hideValue.map(item => {
      item.check = false
      item.data = !item.data ? {} : JSON.parse(item.data)
      return item
    })
    let defaultScene = checkedLeftData.value.filter(item => {
      return item.isDefault == 1
    })

    // 如果有默认场景
    if (defaultScene && defaultScene.length > 0) {
      defaultId.value = defaultScene[0].sceneId
    } else {
      defaultId.value = ''
    }
  }).catch(() => {
  })
}

/**
 * 确定选择
 */
function handleConfirm() {
  // 如果选择默认的 不包含在左侧列表 重置为没有默认
  let leftTemps = checkedLeftData.value.filter(item => {
    return item.sceneId == defaultId.value
  })
  if (leftTemps.length == 0) {
    defaultId.value = ''
  }
  crmSceneSortAPI({
    type: crmTypeModel[props.crmType],
    noHideIds: checkedLeftData.value
        .map(item => item.sceneId),
    hideIds: checkedRightData.value
        .map(item => item.sceneId)
  }).then(res => {
    ElMessage.success({
      message: '操作成功'
    })
    handleCancel()
    emits('save-success')
  }).catch(() => {
  })
}

/**
 * 事项操作
 */
function itemHandle(type, item, index) {
  if (type == 'edit') {
    addAndEditScene('edit', item)
  } else if (type == 'delete') {
    ElMessageBox.confirm('您确定要删除这一条数据吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
        .then(() => {
          crmSceneDeleteAPI({
            sceneId: item.sceneId
          })
              .then(res => {
                ElMessage.success({
                  message: '删除成功'
                })
                checkedLeftData.value.splice(index, 1)
                leftCheckItemChange()
                emits('save-success')
              })
              .catch(() => {
              })
        })
        .catch(() => {
        })
  }
}

/**
 * 操作默认
 */
function defaultHandle(_, item) {
  crmSceneDefaultsAPI({
    sceneId: item.sceneId
  })
      .then(res => {
        ElMessage.success({
          message: '操作成功'
        })
        defaultId.value = item.sceneId
      })
      .catch(() => {
      })
}

/**
 * 添加编辑场景
 */
function addAndEditScene(type, data) {
  filterIndexfieldsAPI({
    label: crmTypeModel[props.crmType]
  })
      .then(res => {
        fieldList.value = res.data.data
        if (type == 'edit') {
          filterObj.value = {form: [], obj: data.data}
          filterName.value = data.name
          filterDefault.value = data.isDefault == 1
          filterEditId.value = data.sceneId.toString()
        } else {
          filterObj.value = {form: []}
          filterEditId.value = ''
          filterName.value = ''
          filterDefault.value = false
        }
        showCreateScene.value = true
      })
      .catch(() => {
      })
}

/**
 * 取消选择
 */
function handleCancel() {
  visible.value = false
  emits('update:dialogVisible', false)
}

/**
 * 拖拽操作
 */
function rightMoveEnd(evt) {
  moveItem.value.check = false
  leftCheckItemChange()
  rightCheckItemChange()
}

function rightMove(obj) {
  moveItem.value = obj.draggedContext.element
}

function leftMoveEnd(evt) {
  moveItem.value.check = false
  leftCheckItemChange()
  rightCheckItemChange()
}

function leftMove(obj) {
  moveItem.value = obj.draggedContext.element
}

// 选择全部
function handleleftCheckAllChange(value) {
  if (value) {
    isleftIndeterminate.value = false
  }
  checkedLeftData.value.forEach(item => {
    item.check = item.isSystem == 1 ? false : value
  })

  leftCheckItems.value = value ? checkedLeftData.value.filter(item => {
    return item.check
  }) : []
}

function leftCheckItemChange() {
  leftCheckItems.value = checkedLeftData.value.filter(item => {
    return item.check == true
  })
  if (leftCheckItems.value.length > 0) {
    if (leftCheckItems.value.length == checkedLeftData.value.length) {
      checkleftAll.value = true
      isleftIndeterminate.value = false
    } else {
      checkleftAll.value = false
      isleftIndeterminate.value = true
    }
  } else {
    checkleftAll.value = false
    isleftIndeterminate.value = false
  }
}

// 选择全部
function handlerightCheckAllChange(value) {
  if (value) {
    isrightIndeterminate.value = false
  }
  checkedRightData.value.forEach(item => {
    item.check = value
  })
  rightCheckItems.value = value ? checkedRightData.value : []
}

function rightCheckItemChange() {
  rightCheckItems.value = checkedRightData.value.filter(item => {
    return item.check == true
  })
  if (rightCheckItems.value.length > 0) {
    if (rightCheckItems.value.length == checkedRightData.value.length) {
      checkrightAll.value = true
      isrightIndeterminate.value = false
    } else {
      checkrightAll.value = false
      isrightIndeterminate.value = true
    }
  } else {
    checkrightAll.value = false
    isrightIndeterminate.value = false
  }
}

// 按钮操作
function changePositon(type) {
  let self = this
  // 从右往左
  if (type == 'left') {
    checkedRightData.value = checkedRightData.value.filter(function (
        item,
        index,
        array
    ) {
      var remove = false
      self.rightCheckItems.forEach(function (element, index) {
        if (item.sceneId == element.sceneId) {
          remove = true
        }
      })
      return !remove
    })

    rightCheckItems.value.forEach(function (element, index) {
      element.check = false
      self.checkedLeftData.push(element)
    })

    rightCheckItems.value = []
    isrightIndeterminate.value = false
    checkrightAll.value = false

    // 刷新左侧效果
    leftCheckItemChange()
    rightCheckItemChange()
  } else {
    checkedLeftData.value = checkedLeftData.value.filter(function (
        item,
        index,
        array
    ) {
      let remove = false
      self.leftCheckItems.forEach(function (element, index) {
        if (item.sceneId == element.sceneId) {
          remove = true
        }
      })
      return !remove
    })

    leftCheckItems.value.forEach(function (element, index) {
      element.check = false
      self.checkedRightData.push(element)
    })

    leftCheckItems.value = []
    isleftIndeterminate.value = false
    checkleftAll.value = false

    // 刷新右侧效果
    leftCheckItemChange()
    rightCheckItemChange()
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.scene-name {
  font-size: 12px;
  padding-bottom: 5px;
  color: #aaa;
}

.default-mark {
  width: 4px;
  height: 4px;
  border-radius: 2px;
  margin-right: 5px;
}

.default-mark-active {
  background-color: $xr-color-primary;
}

.scene-list {
  user-select: none;

  .scene-list-box {
    flex: 1;
    border: 1px solid $xr-border-line-color;
    border-radius: 2px;
    height: 300px;
    position: relative;
    padding: 15px;
  }

  .scene-middle-list {
    width: 50px;
    text-align: center;

    button {
      border: 1px solid #cccccc;
      width: 34px;
      height: 34px;
      border-radius: 17px;
      background-color: #f5f7fa;
    }

    .scene-middle-icon {
      color: #cccccc;
      font-size: 14px;
    }

    .scene-middle-left-button {
    }

    .scene-middle-right-button {
      margin-top: 15px;
      margin-left: 0;
    }

    .scene-middle-button-select {
      //border: 1px solid $xr-color-primary !important;
      background-color: #999999 !important;

      .scene-middle-icon {
        color: white !important;
      }
    }
  }

  .scene-list-head {
    padding-bottom: 15px;
    padding-left: 9px;
    border-bottom: 1px dashed $xr-border-line-color;
    font-size: 13px;

    .scene-list-head-name {
      color: #333;
      flex: 1;
      margin: 0 8px;
    }

    .scene-list-head-detail {
      color: #aaa;
    }
  }

  .scene-list-body {
    padding: 5px 0;
    height: 240px;
    position: relative;
    overflow-y: auto;
  }

  .list-item {
    padding: 5px 0;
    background-color: white;
    height: 26px;
    cursor: pointer;

    .list-item-check {
      margin-right: 8px;
    }

    .list-item-name {
      font-size: 13px;
      color: #333;
      flex: 1;
    }

    .list-item-handle {
      flex-shrink: 0;
      display: none;

      i {
        color: #aaa;
        font-size: 12px;
        margin-right: 5px;
      }

      i:hover {
        color: $xr-color-primary;
      }
    }
  }

  .list-item:hover {
    .list-item-handle {
      display: block;
    }
  }
}

.handle-bar {
  font-size: 12px;

  .handle-bar-add {
    cursor: pointer;
    color: #2362FB;
    padding: 20px 10px 0;
  }

  .handle-bar-save {
    position: relative;
    height: 30px;

    button {
      float: right;
      margin-right: 10px;
    }
  }
}
</style>
